package com.spring.mini.framework.servlet.v1;

import com.spring.mini.framework.annotation.MyAutowired;
import com.spring.mini.framework.annotation.MyController;
import com.spring.mini.framework.annotation.MyRequestMapping;
import com.spring.mini.framework.annotation.MyService;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;

/**
 * @author Tinu 1810989@qq.com
 */
public class MyDispatcherServlet extends HttpServlet {

    private Map<String,Object> mapping = new HashMap<>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            this.doDispatch(req, resp);
        } catch (Exception e) {
            resp.getWriter().write("500 " + Arrays.toString(e.getStackTrace()));
        }
    }

    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String uri = req.getRequestURI();
        String path = req.getContextPath();
        uri = uri.replace(path,"").replaceAll("/+","/");
        if (!this.mapping.containsKey(uri)) {
            resp.getWriter().write("404");
            return;
        }
        Method method = (Method) this.mapping.get(uri);
        Map<String,String[]> params = req.getParameterMap();
        method.invoke(this.mapping.get(method.getDeclaringClass().getName()),new Object[]{req,resp,params.get("name")[0]});

    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        InputStream is = null;
        try {
            // 获取web.xml中 init-param 的参数
            String initParam = config.getInitParameter("contextConfigLocation").replaceFirst("classpath*:","");
            //System.out.println(initParam);
            is = this.getClass().getClassLoader().getResourceAsStream(initParam);
            Properties configContext = new Properties();
            // 加载Properties文件
            configContext.load(is);
            // 读取要扫描的包名
            String scanPackage = configContext.getProperty("scanPackage");
            doScanner(scanPackage);
            for (String className : mapping.keySet()) {
                if(!className.contains(".")){continue;}
                Class<?> clazz = Class.forName(className);
                if (clazz.isAnnotationPresent(MyController.class)) {
                    mapping.put(className,clazz.newInstance());
                    String baseUri = "";
                    if (clazz.isAnnotationPresent(MyRequestMapping.class)) {
                        MyRequestMapping requestMapping = clazz.getAnnotation(MyRequestMapping.class);
                        baseUri = requestMapping.value();
                    }
                    // 得到controller方法
                    Method[] methods = clazz.getMethods();
                    for (Method method : methods) {
                        if (method.isAnnotationPresent(MyRequestMapping.class)) {
                            MyRequestMapping requestMapping = method.getAnnotation(MyRequestMapping.class);
                            String uri = (baseUri + "/" + requestMapping.value()).replaceAll("/+","/");
                            mapping.put(uri, method);
                            System.out.println("Mapped " + uri + "," + method);
                        }
                    }

                } else if (clazz.isAnnotationPresent(MyService.class)) {
                    //System.out.println("clazz.getInterfaces():"+Arrays.toString(clazz.getInterfaces()));
                    MyService service = clazz.getAnnotation(MyService.class);
                    String serviceName = service.value();
                    if ("".equals(serviceName)) serviceName = clazz.getName();
                    Object obj = clazz.newInstance();
                    mapping.put(serviceName,obj);
                    for (Class<?> anInterface : clazz.getInterfaces()) {
                        mapping.put(anInterface.getName(),obj);
                    }
                } else {
                    continue;
                }
            }

            for (Object obj : mapping.values()) {
                if (obj == null) continue;
                Class<?> clazz = obj.getClass();
                if (clazz.isAnnotationPresent(MyController.class)) {
                    Field[] fields = clazz.getDeclaredFields();
                    for (Field field : fields) {
                        if (!field.isAnnotationPresent(MyAutowired.class)) {continue;}
                        MyAutowired autowired = field.getAnnotation(MyAutowired.class);
                        field.setAccessible(true);
                        String beanName = field.getType().getName();
                        field.set(mapping.get(clazz.getName()),mapping.get(beanName));
                    }

                }
            }

            System.out.println("mini StringMVC V1 启动");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    private void doScanner(String scanPackage) {
        URL url = this.getClass().getClassLoader().getResource("/" + scanPackage.replaceAll("\\.","/"));
        File classDir = new File(url.getFile());
        // 循环包下文件
        for (File file : classDir.listFiles()) {
            if (file.isDirectory()) {
                doScanner(scanPackage+"."+file.getName());
            } else {
                if (!file.getName().endsWith(".class")) {continue;}
                String className = scanPackage + "." + file.getName().replace(".class","");
                mapping.put(className,null);
            }
        }


    }
}
